package com.wmlive.hhvideo.heihei.mainhome.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;

import com.baidu.aiupdatesdk.AIUpdateSDK;
import com.baidu.aiupdatesdk.CheckUpdateCallback;
import com.mob.MobSDK;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.base.BaseCompatActivity;
import com.wmlive.hhvideo.common.base.DcBaseActivity;
import com.wmlive.hhvideo.heihei.beans.main.MainHomeStatusEvent;
import com.wmlive.hhvideo.heihei.beans.main.UpdateInfo;
import com.wmlive.hhvideo.heihei.dialog.BaiduUpdateDialog;
import com.wmlive.hhvideo.heihei.discovery.DiscoveryUtil;
import com.wmlive.hhvideo.heihei.discovery.activity.SearchMusicVideoActivity;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.fragment.MainFragment;
import com.wmlive.hhvideo.heihei.mainhome.fragment.ShootFragment;
import com.wmlive.hhvideo.heihei.mainhome.presenter.UpdatePresenter;
import com.wmlive.hhvideo.heihei.mainhome.view.MainActivityView;
import com.wmlive.hhvideo.heihei.personal.PersonalFragment;
import com.wmlive.hhvideo.heihei.personal.activity.FansActivity;
import com.wmlive.hhvideo.heihei.personal.activity.FocusActivity;
import com.wmlive.hhvideo.heihei.personal.activity.PersonalHomeActivity;
import com.wmlive.hhvideo.heihei.recordvideo.DyUIAPIManager;
import com.wmlive.hhvideo.heihei.splash.presenter.SplashPresenter;
import com.wmlive.hhvideo.heihei.splash.view.SplashView;
import com.wmlive.hhvideo.service.DCService;
import com.wmlive.hhvideo.utils.DeviceUtils;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.MyClickListener;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.imageloader.GlideLoader;
import com.wmlive.hhvideo.utils.preferences.SPUtils;
import com.wmlive.hhvideo.utils.update.UpdateUtils;
import com.wmlive.hhvideo.widget.MainTabView;
import com.wmlive.hhvideo.widget.dialog.BaseDialog;
import com.wmlive.hhvideo.widget.dialog.UpDateDialog;
import com.wmlive.networklib.util.RxBus;

import java.util.List;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;
import cn.wmlive.hhvideo.rxbuslib.RxBus2;
import cn.wmlive.hhvideo.rxbuslib.RxBusSubscribe;
import cn.wmlive.hhvideo.rxbuslib.ThreadMode;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.wmlive.hhvideo.application.DCApplication.getDCApp;

/***
 * 首页
 */
public class MainActivity extends DcBaseActivity implements MainActivityView, SplashView {

    private static final String KEY_SHOW_GUIDE = "key_show_guide";
    public static int sMainActTab = 0;

    @BindView(R.id.flContent)
    FrameLayout flContent;
    @BindView(R.id.thTabs)
    FragmentTabHost thTabs;
    @BindView(R.id.ivPublish)
    ImageView ivPublish;
    @BindView(R.id.vs_main_guide)
    ViewStub vsMainGuide;
    ImageView ivMainGuide;
    RelativeLayout rlGuide;

    //标题
    private String[] tabTag;

    public Class[] fragments = {
            MainFragment.class,
            ShootFragment.class,
            PersonalFragment.class};

    //图片
    private int[] tabIcon = {
            R.drawable.bg_tab_home_selector,
            R.drawable.bg_tab_focus_selector,
            R.drawable.bg_tab_personal_selector};

    //tabView
    private MainTabView[] tabCustomerViews = new MainTabView[3];
    String[] permissionParams = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION};

    private SplashPresenter splashPresenter;
    UpdatePresenter mUpdatePresenter;//升级
    private UpDateDialog mUpDateDialog;
    public static int updateApkStatus = -1;//（-1: 默认状态      0：下载中       1：下载完成       2：任务被取消）

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    protected void initData() {
        super.initData();
        sMainActTab = 0;

        changeDecorView(4);
        KLog.i("=========Main1");
        RxBus2.get().register(this);
        KLog.i("=========Main2");
        initTabCustormView();
        KLog.i("=========Main3");
        initTabView();
        KLog.i("=========Main4");
        //初始化share SDK
        MobSDK.init(this);
        KLog.i("=========Main5");

        showGuide();

        initUserInfo();

        KLog.i("=========Main6");
        //检查权限
        checkPermissionsStatus(permissionParams, new BaseCompatActivity.PermissionCallbackInterface() {
            @Override
            public void onPermissionsHasCallback() {
                //通知更新本地视频
                DiscoveryUtil.updateLocalVideo(DCApplication.getDCApp(), null);
            }

            @Override
            public void onPermissionsGrantedCallback(int requestCode, List<String> params) {

            }

            @Override
            public void onPermissionsDeniedCallback(int requestCode, List<String> params) {
                if (params != null) {
                    for (String param : params) {
                        KLog.e("---------------------params-------------------------:" + params);
                    }
                }
                ToastUtil.showToast("请到系统设置里授权 动次 必要的权限，以免影响动次正常使用");
            }
        });
        KLog.i("=========Main7");
        splashPresenter = new SplashPresenter(this);
        mUpdatePresenter = new UpdatePresenter(this);
        //检查更新
        if ("baidu".equals(DeviceUtils.getMetadata(DCApplication.getDCApp(), "UMENG_CHANNEL").toLowerCase())) {
            //百度升级
            AIUpdateSDK.updateCheck(MainActivity.this, checkUpdateCallback);
        } else {
            checkSystemAppUpdate();
        }
        KLog.i("=========Main8");
        addPresenter(splashPresenter, mUpdatePresenter);
        if (GlobalParams.StaticVariable.sInitFromLocal) {
            splashPresenter.init();
        }
    }

    private void initUserInfo() {
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Boolean>() {
                    @Override
                    public Boolean apply(Integer integer) throws Exception {
                        KLog.i("=====开始初始化本地账号信息");
                        AccountUtil.initUserInfo();
                        return true;
                    }
                })
                .observeOn(Schedulers.io())
                .subscribe();
    }

    private void showGuide() {
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Boolean>() {
                    @Override
                    public Boolean apply(Integer integer) throws Exception {
                        return SPUtils.getBoolean(MainActivity.this, KEY_SHOW_GUIDE, false);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            //hide
                            if (vsMainGuide == null) {
                                vsMainGuide = (ViewStub) findViewById(R.id.vs_main_guide);
                            }
                            vsMainGuide.setVisibility(View.GONE);
                        } else {
                            //show
                            if (vsMainGuide == null) {
                                vsMainGuide = (ViewStub) findViewById(R.id.vs_main_guide);
                            }
                            vsMainGuide.inflate();
                            ivMainGuide = (ImageView) findViewById(R.id.iv_main_guide);
                            ivMainGuide.setOnClickListener(MainActivity.this);
                            GlideLoader.loadImage(R.drawable.icon_home_guide, ivMainGuide, R.drawable.icon_home_guide);
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        onRxBusEvent();
        MainHomeStatusEvent event = new MainHomeStatusEvent();
        event.setStatus(MainHomeStatusEvent.MainStatus.RESUME);
        RxBus.getInstance().post(event);
        //检测未编辑完成的视频信息
        checkoutDYUIAPIUnFinishData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        thTabs.getCurrentTab();
        MainHomeStatusEvent event = new MainHomeStatusEvent();
        event.setStatus(MainHomeStatusEvent.MainStatus.PAUSE);
        RxBus.getInstance().post(event);

    }

    /**
     * 初始化自定义tabview
     */
    private void initTabCustormView() {
        tabTag = getResources().getStringArray(R.array.array_main_tab);
        //home 自定义tab
        int tabsLength = tabTag.length;
        for (int j = 0; j < tabsLength; j++) {
            MainTabView mainTabView = new MainTabView(this);
            mainTabView.setTabIcon(tabIcon[j]);
            mainTabView.setTabText(tabTag[j]);
            tabCustomerViews[j] = mainTabView;
        }
    }

    /**
     * 初始化tabview
     */
    private void initTabView() {
        thTabs.setup(this, getSupportFragmentManager(), R.id.flContent);
        for (int i = 0; i < fragments.length; i++) {
            TabHost.TabSpec tabSpec = thTabs.newTabSpec(tabTag[i]).setIndicator(tabCustomerViews[i]);
            thTabs.addTab(tabSpec, fragments[i], null);
        }
        thTabs.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
        thTabs.getTabWidget().getChildTabViewAt(1).setClickable(false);
        thTabs.getTabWidget().getChildTabViewAt(0).setSelected(true);
        thTabs.getTabWidget().getChildTabViewAt(0).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (sMainActTab == 0 || isRecyclerScroll()) {
                    return;
                }
                thTabs.onTabChanged(tabTag[0]);
                sMainActTab = 0;
            }
        });
        ivPublish.setOnClickListener(new MyClickListener() {
            @Override
            protected void onMyClick(View v) {
                if (isRecyclerScroll()) {
                    return;
                }
                if (!AccountUtil.isLogin()) {
                    showReLogin();
                } else {
                    startActivity(new Intent(MainActivity.this, SearchMusicVideoActivity.class));
                }
            }
        });
        thTabs.getTabWidget().getChildTabViewAt(2).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (sMainActTab == 2 || isRecyclerScroll()) {
                    return;
                }
                if (!AccountUtil.isLogin()) {
                    showReLogin();
                } else {
                    sMainActTab = 2;
                    thTabs.onTabChanged(tabTag[2]);
                }
            }
        });

        thTabs.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                resetTabsSelectionState(tabId);
            }
        });
        //默认选中第一
        thTabs.onTabChanged(tabTag[0]);
    }


    private boolean isRecyclerScroll() {
        Fragment fragment = getSupportFragmentManager().getFragments().get(0);
        if (null != fragment && fragment instanceof MainFragment) {
            return ((MainFragment) fragment).isRecyclerScroll();
        }
        return false;
    }

    /**
     * 检测未编辑完成的数据
     */
    private void checkoutDYUIAPIUnFinishData() {
        DyUIAPIManager.getInstance().onCheckUnFinishData(MainActivity.this);
    }

    /**
     * 恢复tabs选中状态
     */
    private void resetTabsSelectionState(String tabId) {
        for (MainTabView mMainTabView : tabCustomerViews) {
            if (mMainTabView != null) {
                mMainTabView.showView(View.INVISIBLE);
            }
        }
        if (!TextUtils.isEmpty(tabId)) {
            for (MainTabView mMainTabView : tabCustomerViews) {
                if (mMainTabView != null && tabId.equals(mMainTabView.getTvText())) {
                    mMainTabView.showView(View.VISIBLE);
                    break;
                }
            }
        }

    }

    /**
     * 默认指定选中tab
     */
    @RxBusSubscribe(code = GlobalParams.EventType.TYPE_SHOW_MAIN_FIRST, threadMode = ThreadMode.MAIN)
    public void showTabsByIndex(Boolean iFlag) {
        if (thTabs != null) {
            thTabs.post(new Runnable() {
                @Override
                public void run() {
                    thTabs.getTabWidget().getChildTabViewAt(0).performClick();
                }
            });

        }
    }


    @Override
    protected void onSingleClick(View v) {
        if (v.getId() == R.id.iv_main_guide) {
            SPUtils.putBoolean(this, KEY_SHOW_GUIDE, true);
            if (vsMainGuide != null) {
                vsMainGuide.setVisibility(View.GONE);
            }
        }
    }

    private void onRxBusEvent() {


    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus2.get().unRegister(this);
        stopDCService();
    }

    private void stopDCService() {
        Intent intent = new Intent(this, DCService.class);
        stopService(intent);
    }

    public static Intent getCallingIntent(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return intent;
    }

    long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToast("再按一次退出应用");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                getDCApp().exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * token失效重新登录的事件
     *
     * @param rxBusMessage
     */
    @RxBusSubscribe(code = GlobalParams.EventType.TYPE_RELOGIN, threadMode = ThreadMode.MAIN)
    public void onReLoginEvent(Boolean rxBusMessage) {
        Activity activity = DCApplication.getDCApp().getCurrentActivity();
        KLog.i("======收到消息：" + rxBusMessage + "_" + activity);
        //清除账号信息
        AccountUtil.clearAccount();
        if (null != activity && activity instanceof DcBaseActivity) {
            if (activity instanceof PersonalHomeActivity || activity instanceof FocusActivity || activity instanceof FansActivity) {

            } else {
                ((DcBaseActivity) activity).showReLogin();
            }
        }
    }
//===================================升级接口========================================

    /**
     * 检查升级接口
     */
    private void checkSystemAppUpdate() {
        mUpdatePresenter.checkSystemAppUpdate(String.valueOf(GlobalParams.Config.APP_VERSION), DeviceUtils.getMetadata(DCApplication.getDCApp(), "UMENG_CHANNEL"));
    }

    @Override
    public void checkSystemAppUpdateSucceed(final UpdateInfo updateInfo) {
        if (updateInfo != null && !TextUtils.isEmpty(updateInfo.getApp_url())) {
            mUpDateDialog = new UpDateDialog(MainActivity.this);
            mUpDateDialog.setTitle(updateInfo.getTips_title());
            if (updateInfo.isForce()) {
                mUpDateDialog.setBtnCancelVisibity(View.GONE);
            }
            mUpDateDialog.setContent(updateInfo.getTips_text());
            mUpDateDialog.setBtnOKText(getText(R.string.update_information_ok));
            mUpDateDialog.setCancelable(!updateInfo.isForce());
//            updateDialog.setButOKEnable(true);
            mUpDateDialog.setBaseDialogOnclicklistener(new BaseDialog.BaseDialogOnclicklistener() {

                @Override
                public void onOkClick(Dialog dialog) {
                    UpdateUtils.download(MainActivity.this, updateInfo.getApp_url(), updateInfo.getApp_name(), updateInfo.getFile_name());
                    if (!updateInfo.isForce()) {
                        mUpDateDialog.dismiss();
                    } else {
                        //强制升级
                        mUpDateDialog.setBtnOKText(getText(R.string.update_loading));
                    }
                }

                @Override
                public void onCancleClick(Dialog dialog) {
                    mUpDateDialog.dismiss();
                }
            });
            mUpDateDialog.show();
        }
    }

    @Override
    public void checkSystemAppUpdateFailure(String error_msg) {

    }

    //===============================百度升级================================
    private CheckUpdateCallback checkUpdateCallback = new CheckUpdateCallback() {
        @Override
        public void onCheckUpdateCallback(com.baidu.aiupdatesdk.UpdateInfo updateInfo) {
            if (null != updateInfo) {
                final BaiduUpdateDialog updateBaiduDialog = new BaiduUpdateDialog(MainActivity.this);
                if (updateInfo.isForceUpdate()) {
                    updateBaiduDialog.setBtnCancelVisibity(View.GONE);
                }
                updateBaiduDialog.setCancelable(!updateInfo.isForceUpdate());
                updateBaiduDialog.setContent(Html.fromHtml(updateInfo.getChangeLog()));
                updateBaiduDialog.setBtnOKText("智能升级");
                updateBaiduDialog.setBtnCancelText("暂不升级");
                updateBaiduDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            return true;
                        }
                        return false;
                    }
                });
                updateBaiduDialog.setForceUpdate(updateInfo.isForceUpdate());
                updateBaiduDialog.setBaseDialogOnclicklistener(new BaseDialog.BaseDialogOnclicklistener() {

                    @Override
                    public void onOkClick(Dialog dialog) {
                        AIUpdateSDK.updateDownload(MainActivity.this);
                        updateBaiduDialog.dismiss();
                    }

                    @Override
                    public void onCancleClick(Dialog dialog) {
                        updateBaiduDialog.dismiss();
                    }
                });
                updateBaiduDialog.show();
            }
        }
    };


    @Override
    public void initApiError(String msg) {

    }

    @Override
    public void initApiSucceed() {

    }

    @Override
    public void onInitComplete() {

    }
}
